import {
  createRouter,
  createWebHistory,
  type NavigationGuardNext,
  type RouteLocationNormalized,
} from "vue-router";
import useStore from "@/stores";
import { routes } from "@/router/routes";
const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: routes,
});

// 路由前置拦截器
router.beforeEach(
  async (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    if (to.name === "404") {
      next();
      return;
    }

    const notAuthRouteNameList = ["login"];

    if (!notAuthRouteNameList.includes(to.name ? to.name.toString() : "")) {
      const { user } = useStore();
      const token = user.getToken();
      if (!token) {
        next({
          path: "/login",
        });
        return;
      }
      if (!user.userInfo) {
        await user.getUserInfo(localStorage.getItem("userAcc") as string);
      }
    }
    next();
  }
);

export default router;
